/*java jdk 1.7+
# -*- coding: utf-8 -
'''
Created on 2020年05月10日
@author: zxyong 13738196011
'''*/

package com.zxy.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.SortedMap;

public class Sha1Util
{
	public static String getNonceStr() throws Exception
	{
		Random random = new Random();
		return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)),"UTF-8");
	}

	public static String getTimeStamp()
	{
		return String.valueOf(System.currentTimeMillis() / 1000L);
	}

	public static String createSHA1Sign(SortedMap<String, String> signParams) throws Exception
	{
		StringBuffer sb = new StringBuffer();
		Set<Map.Entry<String, String>> es = signParams.entrySet();
		Iterator<Map.Entry<String, String>> it = es.iterator();
		while(it.hasNext())
		{
			Map.Entry entry = (Map.Entry) it.next();
			String k = (String) entry.getKey();
			String v = (String) entry.getValue();
			sb.append(k + "=" + v + "&");
		}
		String params = sb.substring(0,sb.lastIndexOf("&"));
		return getSha1(params);
	}

	public static String DefSha1(String str) throws Exception
	{
		// 获取指定摘要算法的messageDigest对象
		MessageDigest messageDigest;
		byte[] cipherBytes = null;
		messageDigest = MessageDigest.getInstance("SHA-1");
		cipherBytes = messageDigest.digest(str.getBytes());
		String cipherStr = Com_Fun.bytesToHexString(cipherBytes);
		return cipherStr;
	}

	public static String getSha1(String str) throws Exception
	{
		if((java.util.Objects.equals(str,null)) || (str.length() == 0))
		{
			return null;
		}
		char[] hexDigits =
		{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
				'e', 'f' };
		MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
		mdTemp.update(str.getBytes("GBK"));
		byte[] md = mdTemp.digest();
		int j = md.length;
		char[] buf = new char[j * 2];
		int k = 0;
		for(int i = 0;i < j;i++)
		{
			byte byte0 = md[i];
			buf[(k++)] = hexDigits[(byte0 >>> 4 & 0xF)];
			buf[(k++)] = hexDigits[(byte0 & 0xF)];
		}
		return new String(buf);
	}
}